<template>
  <div class="inventory-analysis">
    <el-row :gutter="20" v-if="!loading">
      <el-col :span="24">
        <el-card class="overview-card" shadow="hover">
          <template #header>
            <div class="card-header">
              <h3>库存概览</h3>
            </div>
          </template>
          <el-row :gutter="20">
            <el-col :xs="24" :sm="12" :md="8" :lg="6">
              <div class="stat-box">
                <div class="stat-value">{{ inventoryData.totalProducts }}</div>
                <div class="stat-label">商品总数</div>
              </div>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6">
              <div class="stat-box">
                <div class="stat-value">{{ inventoryData.inStockProducts }}</div>
                <div class="stat-label">有库存商品</div>
              </div>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6">
              <div class="stat-box warning">
                <div class="stat-value">{{ inventoryData.lowStockProducts }}</div>
                <div class="stat-label">库存不足</div>
              </div>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6">
              <div class="stat-box danger">
                <div class="stat-value">{{ inventoryData.outOfStockProducts }}</div>
                <div class="stat-label">库存耗尽</div>
              </div>
            </el-col>
          </el-row>
        </el-card>
      </el-col>
      
      <el-col :span="24" class="mt-20">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <h3>库存分布</h3>
            </div>
          </template>
          <div class="chart-container">
            <div ref="inventoryDistributionChart" class="chart"></div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="24" class="mt-20">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <h3>按分类库存状态</h3>
            </div>
          </template>
          <el-table :data="inventoryData.categoryInventory" stripe style="width: 100%">
            <el-table-column prop="category" label="分类" width="180" />
            <el-table-column prop="totalProducts" label="商品数量" width="120" />
            <el-table-column prop="avgStock" label="平均库存" width="120" />
            <el-table-column prop="totalStock" label="总库存" width="120" />
            <el-table-column prop="lowStock" label="库存不足" width="120" />
            <el-table-column prop="outOfStock" label="无库存" width="120" />
            <el-table-column label="库存状态" width="180">
              <template #default="scope">
                <el-progress
                  :percentage="calculateStockPercentage(scope.row)"
                  :status="getStockStatus(scope.row)"
                />
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
      
      <el-col :span="24" class="mt-20">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <h3>需要补货的商品</h3>
            </div>
          </template>
          <el-table :data="inventoryData.lowStockItems" stripe style="width: 100%">
            <el-table-column prop="productId" label="商品ID" width="100" />
            <el-table-column prop="name" label="商品名称" min-width="200" />
            <el-table-column prop="category" label="分类" width="120" />
            <el-table-column prop="currentStock" label="当前库存" width="120" />
            <el-table-column prop="warningLevel" label="警戒库存" width="120" />
            <el-table-column prop="reorderLevel" label="补货库存" width="120" />
            <el-table-column label="库存状态" width="180">
              <template #default="scope">
                <el-tag 
                  :type="scope.row.currentStock === 0 ? 'danger' : 'warning'"
                  effect="dark"
                >
                  {{ scope.row.currentStock === 0 ? '无库存' : '库存不足' }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
      
      <el-col :span="24" class="mt-20">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <h3>库存周转率</h3>
              <span class="subtitle">过去30天内库存周转情况</span>
            </div>
          </template>
          <div class="chart-container">
            <div ref="turnoverRateChart" class="chart"></div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <div v-if="loading" class="loading-container">
      <el-skeleton style="width: 100%">
        <template #template>
          <el-skeleton-item variant="h3" style="width: 30%" />
          <el-skeleton-item variant="text" style="margin-top: 20px; width: 100%" />
          <el-skeleton-item variant="text" style="width: 100%" />
          <el-skeleton-item variant="text" style="width: 100%" />
        </template>
      </el-skeleton>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from 'vue'
import * as echarts from 'echarts'

// 属性
const props = defineProps({
  dateRange: {
    type: Array,
    required: true
  },
  loading: {
    type: Boolean,
    default: false
  },
  reportData: {
    type: Object,
    default: () => ({})
  }
})

const emit = defineEmits(['refresh'])

// 图表引用
const inventoryDistributionChart = ref(null)
const turnoverRateChart = ref(null)

// 模拟数据 - 实际项目中应该从 props.reportData 获取
const inventoryData = reactive({
  totalProducts: 235,
  inStockProducts: 198,
  lowStockProducts: 27,
  outOfStockProducts: 10,
  
  categoryInventory: [
    { category: '啤酒', totalProducts: 78, avgStock: 24, totalStock: 1872, lowStock: 8, outOfStock: 2 },
    { category: '红酒', totalProducts: 42, avgStock: 15, totalStock: 630, lowStock: 6, outOfStock: 3 },
    { category: '白酒', totalProducts: 35, avgStock: 18, totalStock: 630, lowStock: 4, outOfStock: 1 },
    { category: '洋酒', totalProducts: 30, avgStock: 12, totalStock: 360, lowStock: 5, outOfStock: 2 },
    { category: '饮料', totalProducts: 50, avgStock: 35, totalStock: 1750, lowStock: 4, outOfStock: 2 }
  ],
  
  lowStockItems: [
    { productId: '100231', name: '青岛啤酒500ml', category: '啤酒', currentStock: 3, warningLevel: 10, reorderLevel: 20 },
    { productId: '100156', name: '拉菲红酒750ml', category: '红酒', currentStock: 2, warningLevel: 5, reorderLevel: 10 },
    { productId: '100789', name: '五粮液500ml', category: '白酒', currentStock: 0, warningLevel: 5, reorderLevel: 10 },
    { productId: '100432', name: '杰克丹尼威士忌700ml', category: '洋酒', currentStock: 1, warningLevel: 5, reorderLevel: 8 },
    { productId: '100985', name: '可口可乐330ml', category: '饮料', currentStock: 4, warningLevel: 20, reorderLevel: 40 }
  ],
  
  inventoryDistribution: [
    { name: '库存充足', value: 198 },
    { name: '库存不足', value: 27 },
    { name: '无库存', value: 10 }
  ],
  
  turnoverRates: [
    { category: '啤酒', rate: 4.2 },
    { category: '红酒', rate: 1.8 },
    { category: '白酒', rate: 2.3 },
    { category: '洋酒', rate: 1.5 },
    { category: '饮料', rate: 5.6 }
  ]
})

// 计算库存百分比
function calculateStockPercentage(row) {
  const inStock = row.totalProducts - row.lowStock - row.outOfStock
  return Math.round((inStock / row.totalProducts) * 100)
}

// 获取库存状态
function getStockStatus(row) {
  const percentage = calculateStockPercentage(row)
  if (percentage < 70) return 'warning'
  if (percentage < 50) return 'exception'
  return 'success'
}

// 初始化库存分布图表
function initInventoryDistributionChart() {
  if (!inventoryDistributionChart.value) return
  
  const chart = echarts.init(inventoryDistributionChart.value)
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'horizontal',
      bottom: 10,
      data: inventoryData.inventoryDistribution.map(item => item.name)
    },
    series: [
      {
        name: '库存分布',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '18',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: [
          { 
            value: inventoryData.inStockProducts, 
            name: '库存充足',
            itemStyle: { color: '#67C23A' }
          },
          { 
            value: inventoryData.lowStockProducts, 
            name: '库存不足',
            itemStyle: { color: '#E6A23C' }
          },
          { 
            value: inventoryData.outOfStockProducts, 
            name: '无库存',
            itemStyle: { color: '#F56C6C' }
          }
        ]
      }
    ]
  }
  
  chart.setOption(option)
  
  // 响应窗口大小变化
  window.addEventListener('resize', () => {
    chart.resize()
  })
}

// 初始化周转率图表
function initTurnoverRateChart() {
  if (!turnoverRateChart.value) return
  
  const chart = echarts.init(turnoverRateChart.value)
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'value',
      boundaryGap: [0, 0.01],
      name: '周转率'
    },
    yAxis: {
      type: 'category',
      data: inventoryData.turnoverRates.map(item => item.category)
    },
    series: [
      {
        name: '库存周转率',
        type: 'bar',
        data: inventoryData.turnoverRates.map(item => item.rate),
        itemStyle: {
          color: function(params) {
            // 周转率越高颜色越深
            const rate = inventoryData.turnoverRates[params.dataIndex].rate
            if (rate > 4) return '#67C23A'
            if (rate > 2) return '#409EFF'
            return '#E6A23C'
          }
        }
      }
    ]
  }
  
  chart.setOption(option)
  
  // 响应窗口大小变化
  window.addEventListener('resize', () => {
    chart.resize()
  })
}

// 监听日期范围变化
watch(() => props.dateRange, () => {
  if (props.dateRange && props.dateRange.length === 2) {
    emit('refresh')
  }
}, { deep: true })

// 组件挂载后初始化图表
onMounted(() => {
  // 模拟延迟加载
  setTimeout(() => {
    initInventoryDistributionChart()
    initTurnoverRateChart()
  }, 500)
})
</script>

<style scoped>
.inventory-analysis {
  width: 100%;
}

.mt-20 {
  margin-top: 20px;
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.card-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.subtitle {
  font-size: 14px;
  color: #909399;
}

.overview-card {
  margin-bottom: 20px;
}

.stat-box {
  padding: 20px;
  text-align: center;
  background-color: #f5f7fa;
  border-radius: 4px;
  margin-bottom: 15px;
}

.stat-value {
  font-size: 26px;
  font-weight: bold;
  color: #409EFF;
}

.stat-box.warning .stat-value {
  color: #E6A23C;
}

.stat-box.danger .stat-value {
  color: #F56C6C;
}

.stat-label {
  font-size: 14px;
  color: #606266;
  margin-top: 8px;
}

.chart-container {
  width: 100%;
  height: 400px;
}

.chart {
  width: 100%;
  height: 100%;
}

.loading-container {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
</style> 